<template>
	<div>
		<!-- 面包屑导航区 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
		  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
		  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片视图 -->
		<el-card>
			<!-- 添加角色按钮区域 -->
			<el-row>
				<el-col>
					<el-button type="primary" @click="addRolesDialogVisible=true">添加角色</el-button>
				</el-col>
			</el-row>
			<!-- 角色列表区域 -->
			<el-table :data="roleList" border stripe>
				<!-- 展开列 -->
				<el-table-column type="expand">
					<template v-slot="scope">
						<!-- 渲染栅格 -->
						<el-row v-for="(item1,i1) in scope.row.children" 
						:key="item1.id"
						:class="['bdbottom',i1===0? 'bdtop' :'','vcenter']">
							<!-- 渲染一级权限 -->
							<el-col :span="5">
								<el-tag
								closable
								@close="removeRightById(scope.row,item1.id)">
									{{item1.authName}}
								</el-tag>
								<i class="el-icon-caret-right"></i>
							</el-col>
							<!-- 渲染二级三级权限 -->
							<el-col :span="19">
								<!-- 通过for循环嵌套渲染二级权限 -->
								<el-row v-for="(item2,i2) in item1.children" 
								:key="item2.id"
								:class="[i2===0 ? '':'bdtop','vcenter']">
									<!-- 渲染二级权限 -->
									<el-col :span="6">
										<el-tag type="success"
										closable
										@close="removeRightById(scope.row,item2.id)">
											{{item2.authName}}
										</el-tag>
										<i class="el-icon-caret-right"></i>
									</el-col>
									<el-col :span="18">
										<el-tag v-for="(item3,i3) in item2.children"
										:key="item3.id"
										type="warning"
										closable
										@close="removeRightById(scope.row,item3.id)">
											{{item3.authName}}
										</el-tag>
									</el-col>
								</el-row>
							</el-col>
						</el-row>
						<!-- <pre>
							{{scope.row}}
						</pre> -->
					</template>
				</el-table-column>
				<!-- 索引列 -->
				<el-table-column type="index" label="#"></el-table-column>
				<el-table-column label="角色名称" prop="roleName"></el-table-column>
				<el-table-column label="角色描述" prop="roleDesc"></el-table-column>
				<el-table-column label="操作" >
					<template v-slot="scope">
						<el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditRolesDialog(scope.row.id)">编辑</el-button>
						<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRolesById(scope.row.id)">删除</el-button>
						<el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<!-- 添加编辑区域 对话框 -->
		<el-dialog
		  title="添加角色"
		  :visible.sync="addRolesDialogVisible"
		  width="50%"
		  @close="addRolesDialogClosed">
		  <!-- 内容主题区 -->
		  <el-form :model="addRolesForm" :rules="addRolesRules" ref="addRolesRef" label-width="110px">
		    <el-form-item label="添加角色名称" prop="roleName">
		      <el-input v-model="addRolesForm.roleName"></el-input>
		    </el-form-item>
			<el-form-item label="添加角色描述" prop="roleDesc">
			  <el-input v-model="addRolesForm.roleDesc"></el-input>
			</el-form-item>
		   </el-form>
		  <!-- 底部按钮区域 -->
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="addRolesDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="addRoles">确 定</el-button>
		  </span>
		</el-dialog>
		<!-- 修改编辑区域对话框 -->
		<el-dialog
		  title="修改角色"
		  :visible.sync="editRolesDialogVisible"
		  width="50%"
		  @close="editRolesDialogClosed">
		  <el-form :model="editRolesForm" :rules="editRolesFormRules" ref="editRolesFormRef" label-width="110px">
		    <el-form-item label="角色名称" prop="roleName">
		      <el-input v-model="editRolesForm.roleName"></el-input>
		    </el-form-item>
			<el-form-item label="角色描述" prop="roleDesc">
			  <el-input v-model="editRolesForm.roleDesc"></el-input>
			</el-form-item>
		   </el-form>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="editRolesDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="editRolesInfo">确 定</el-button>
		  </span>
		</el-dialog>
        <!-- 分配权限按钮对话框 -->
		<el-dialog
		  title="分配权限"
		  :visible.sync="setRightDialogVisible"
		  width="50%" @close="setRightDialogClosed">
		  <el-tree :data="rightsList" :props="treeProps" 
		  show-checkbox node-key="id" 
		  default-expand-all
		  :default-checked-keys="defKeys"
		  ref="treeRef"></el-tree>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="setRightDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="allotRights">确 定</el-button>
		  </span>
		</el-dialog>		
	</div>
</template>

<script>
	export default{
		data(){
			return{
				//所有角色列表
				roleList:[],
				//所有权限列表
				rightsList:[],
				//控制添加用户对话框的隐藏和显示
				addRolesDialogVisible:false,
				//添加用户的表单数据
				addRolesForm:{
					roleName:'',
					roleDesc:''
				},
				//添加表单的验证规则对象
				addRolesRules:{
					roleName:[
						{required:true,message:'请输入角色名称',trigger:'blur'},
					]
				},
				//控制修改角色对话框的隐藏和显示
				editRolesDialogVisible:false,
				//修改角色的表单验证
				editRolesForm:{},
				editRolesFormRules:{
					roleName:[
						{required:true,message:'请输入角色名称',trigger:'blur'},
					]
				},
				//控制分配权限对话框的显示和隐藏
				setRightDialogVisible:false,
				//树形控件的属性绑定对象
				treeProps:{					
					children:'children',
					label:'authName'
				},
				//默认打开选择节点的数组
				defKeys:[],
				//分配权限的id值
				roleId:''			
			}
		},
		created(){
			this.getRolesList()
		},
		methods:{
			//获取所有角色列表
			async getRolesList(){
				const {data:res}=await this.$http.get('roles')
				if(res.meta.status!==200){
					return this.$message.error('获取角色列表失败！')
				}
				this.roleList=res.data
				//console.log(this.roleList)
			},
			//监听添加对话框关闭
			addRolesDialogClosed(){
				this.$refs.addRolesRef.resetFields()
			},
			//点击按钮 添加新用户
			addRoles(){
				this.$refs.addRolesRef.validate(async valid=>{
					if(!valid) return
					const {data:res}=await this.$http.post('roles',this.addRolesForm)
					if(res.meta.status!==201){
						return this.$message.error('添加角色失败')
					}
					//隐藏添加对象框
					this.addRolesDialogVisible=false
					//刷新角色列表数据
					this.getRolesList()
					//添加成功提示信息
					this.$message.success('添加角色成功')
				})
			},
			//展示编辑角色的对话框
			async showEditRolesDialog(id){
				const {data:res}=await this.$http.get('roles/'+id)
				if(res.meta.status!==200){
					return this.$message.error('查询角色失败！')
				}
				this.editRolesForm=res.data
				this.editRolesDialogVisible=true
			},
			//修改内容的重置  修改角色对话框的关闭事件
			editRolesDialogClosed(){
				this.$refs.editRolesFormRef.resetFields()
			},
			//修改信息的提交
			editRolesInfo(){
				this.$refs.editRolesFormRef.validate(async valid=>{
					console.log(valid)
					if(!valid) return
					const {data:res}=await this.$http.put('roles/'+this.editRolesForm.roleId,
					{roleName:this.editRolesForm.roleName,roleDesc:this.editRolesForm.roleDesc})
					if(res.meta.status!==200){
						return this.$message.error('修改角色失败！')
					}
						this.editRolesDialogVisible=false	
						this.getRolesList()
						this.$message.success('更新角色信息成功')
						
					})				
			},
			//根据id删除角色
			async removeRolesById(id){
				const confirmResult=await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
								          confirmButtonText: '确定',
								          cancelButtonText: '取消',
								          type: 'warning'
				}).catch(err=>err)
						//如果用户确认删除 返回的是字符串 confirm
						//如果用户取消删除 catch 捕获错误信息 cancel
						//console.log(confirmResult)
			    if(confirmResult!=='confirm'){
			    	return this.$message.info('已经取消删除')
			    }
				//发起请求，删除信息
				 const {data:res}=await this.$http.delete('roles/'+id)
				 if(res.meta.status!==200){
				 	return this.$message.error('删除用户失败！')
				 } 
				 this.$message.success('删除成功')
				 this.getRolesList()
			},		
			//根据id删除对应权限
			async removeRightById(role,rightId){
				//弹框提示是否删除
				const confirmResult=await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning'
				}).catch(err=>err)
				if(confirmResult!=='confirm'){
					return this.$message.info('取消了删除')
				}
				const {data:res}=await this.$http.delete(`roles/${role.id}/rights/${rightId}`)				
				if(res.meta.status!==200){
					return this.$message.error('删除权限失败！')
				}
				console.log(res)
				//this.$message.success('删除权限成功！')
				role.children=res.data
			},
			//展示分配权限对话框
			async showSetRightDialog(role){
				//获取所有权限数据
				this.roleId=role.id
				const {data:res}=await
				this.$http.get('rights/tree')
				if(res.meta.status!==200){
					return this.$message.error('获取用户权限失败')
				}
				this.rightsList=res.data
				//递归获取三级节点的id
				this.getLeafKeys(role,this.defKeys)
				this.setRightDialogVisible=true
			},
			//通过递归的形式，获取角色下的所有三级权限的id 并保存到defkeys数组中
			getLeafKeys(node,arr){
				if(!node.children){
					//如果当前node节点不包含children属性 则是三级节点
					return arr.push(node.id)
				}
				node.children.forEach(item=>
				this.getLeafKeys(item,arr))
			},
			//监听权限分配关闭和开启
			setRightDialogClosed(){
				this.defKeys=[]
			},
			//为角色分配权限
			async allotRights(){
				const keys=[
					...this.$refs.treeRef.getCheckedKeys(),
					...this.$refs.treeRef.getHalfCheckedKeys()
				]
				const idStr=keys.join(',')
				const {data:res}=
				await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
				if(res.meta.status!==200){
					return this.$message.error('分配权限失败')
				}
				this.setRightDialogVisible=false
				this.getRolesList()				
			}			
		}
	}
</script>

<style scoped>
	.el-tag{
		margin: 7px;
	}
	.bdtop{
		border-top: 1px solid #eee;
	}
	.bdbottom{
		border-bottom: 1px solid #eee;
	}
	.vcenter{
		display: flex;
        align-items: center;
	}
</style>
